package com.aerozhonghuan.logisticsmall.modules.common;

import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;

import com.aerozhonghuan.foundation.base.BaseActivity;
import com.aerozhonghuan.foundation.base.BaseFragment;
import com.aerozhonghuan.foundation.eventbus.EventBusManager;
import com.aerozhonghuan.foundation.log.LogUtil;
import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.framework.DB.DBAdapter;
import com.aerozhonghuan.logisticsmall.modules.cart.CartFragment;
import com.aerozhonghuan.logisticsmall.modules.common.entity.GoodsObject;
import com.aerozhonghuan.logisticsmall.modules.common.event.DefalutHttpExceptionAlert;
import com.aerozhonghuan.logisticsmall.modules.common.event.HaveUnreadMessageEvent;
import com.aerozhonghuan.logisticsmall.modules.common.event.TabNumberChangedEvent;
import com.aerozhonghuan.logisticsmall.modules.common.event.UserInfoChangedEvent;
import com.aerozhonghuan.logisticsmall.modules.common.event.UserInfoChangedSuccessEvent;
import com.aerozhonghuan.logisticsmall.modules.home.AddProductToGouwuche;
import com.aerozhonghuan.logisticsmall.modules.home.HomeFragment;
import com.aerozhonghuan.logisticsmall.modules.mine.MineFragment;
import com.aerozhonghuan.logisticsmall.modules.mine.logic.MineWebRequest;
import com.aerozhonghuan.logisticsmall.modules.sort.SortFragment;
import com.aerozhonghuan.logisticsmall.modules.user.beans.UserBean;
import com.aerozhonghuan.logisticsmall.modules.user.logic.LoginLogic;
import com.aerozhonghuan.logisticsmall.modules.user.logic.UserInfoManager;
import com.aerozhonghuan.logisticsmall.utils.StatusBarUtil;
import com.aerozhonghuan.logisticsmall.widget.TabButton;
import com.aerozhonghuan.oknet2.CommonCallback;
import com.aerozhonghuan.oknet2.CommonMessage;
import com.aerozhonghuan.zh_map.ZHSDKInitializer;
import com.example.updatelibrary.DeleteOrStopLoadEvent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * 描述: MainActivity show/hide fragment
 * tab为自定义TabButton,可以设置消息数量,红点提示
 * 作者:zhangyonghui
 * 创建日期：2017/6/20  on 上午 11:27
 */
public class MainActivity extends BaseActivity implements View.OnClickListener, IMainView, AddProductToGouwuche {

    private static final String TAG = "MainActivity";
    // 第二次按返回键推出程序的时间间隔，4秒
    private final int mInterval = 1000;
    private static List<TabButton> buttonList = new ArrayList<>();
    private List<BaseFragment> fragmentList = new ArrayList<>();
    public static MainActivity sMainActivity;
    private BaseFragment currentFragment;
    // 记录首次按退出键时的时间
    private long mExitTime = 0;
    private DBAdapter dbAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ZHSDKInitializer.init(getApplicationContext());
        setContentView(R.layout.activity_main);
        sMainActivity = this;
        StatusBarUtil.setLightStatusBar(this, true);
        EventBusManager.register(this);
        initView();
        initData();
        initEvent();
    }

    private void initData() {
        dbAdapter = new DBAdapter(this);
    }

    private void checkUnreadMessage() {
        MineWebRequest.isHaveUnreadMsg(this, new CommonCallback<String>() {
            @Override
            public void onSuccess(String messsageBodyObject, CommonMessage commonMessage, String allResponseString) {
                try {
                    JSONObject jsonObject = new JSONObject(messsageBodyObject);
                    int message = jsonObject.getInt("message");
                    if (message == 1) {
                        EventBusManager.postSticky(new HaveUnreadMessageEvent());
                        buttonList.get(TAB_MINE_FRAGMENT).showRedPoint(true);
                    } else {
                        buttonList.get(TAB_MINE_FRAGMENT).showRedPoint(false);
                    }
                } catch (Exception e) {
                    buttonList.get(TAB_MINE_FRAGMENT).showRedPoint(false);
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getExtras() != null && intent.getExtras().containsKey("tab")) {
            int tab = Integer.valueOf(intent.getStringExtra("tab"));
            if (currentFragment != fragmentList.get(Integer.valueOf(intent.getStringExtra("tab")))) {
                select(tab);
                showFragment2(fragmentList.get(tab));
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getCurrentTab() != TAB_MINE_FRAGMENT) {
            checkUnreadMessage();
        }
        if (getCurrentTab() != TAB_CART_FRAGMENT) {
            ArrayList<GoodsObject> allData = dbAdapter.getAllData();
            int productSize = 0;
            for (GoodsObject product : allData) {
                if (product.getIsCheck() == 0) {
                    productSize += product.getIntoGouwucheSize();
                }
            }
            EventBusManager.post(new TabNumberChangedEvent(TAB_CART_FRAGMENT, productSize));
        }
    }

    @Override
    public int getCurrentTab() {
        if (currentFragment instanceof HomeFragment) {
            return TAB_HOME_FRAGMENT;
        } else if (currentFragment instanceof MineFragment) {
            return TAB_MINE_FRAGMENT;
        } else {
            return 0;
        }
    }

    /**
     * 设置当前标签选中
     *
     * @param number
     */
    public void select(int number) {
        for (TabButton btn : buttonList) {
            btn.setSelect(false);
        }
        buttonList.get(number).setSelect(true);
    }

    private void initView() {
        LogUtil.d(TAG, "buttonList::"+buttonList.size());
        if (buttonList.size() > 0) {
            buttonList.clear();
        }
        if (fragmentList.size() > 0) {
            fragmentList.clear();
        }
        buttonList.add((TabButton) findViewById(R.id.tab_home));
        buttonList.add((TabButton) findViewById(R.id.tab_sort));
        buttonList.add((TabButton) findViewById(R.id.tab_cart));
        buttonList.add((TabButton) findViewById(R.id.tab_user));
        fragmentList.add(new HomeFragment());
        fragmentList.add(new SortFragment());
        fragmentList.add(new CartFragment());
        fragmentList.add(new MineFragment());
        // 设置首页默认选中
        buttonList.get(TAB_HOME_FRAGMENT).setSelect(true);
        showFragment2(fragmentList.get(TAB_HOME_FRAGMENT));
    }

    private void initEvent() {
        // 为每一个标签添加事件和tag
        for (int i = 0; i < buttonList.size(); i++) {
            buttonList.get(i).setOnClickListener(this);
            buttonList.get(i).setTag(i);
        }
    }

    /**
     * 使用show() hide()切换页面
     * 显示fragment
     */
    private void showFragment2(BaseFragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (fragmentList.indexOf(fragment) > fragmentList.indexOf(currentFragment) && currentFragment != null) {
            transaction.setCustomAnimations(R.anim.push_right_in, R.anim.push_left_out, R.anim.push_left_in, R.anim.push_right_out);
        } else if (fragmentList.indexOf(fragment) < fragmentList.indexOf(currentFragment) && currentFragment != null) {
            transaction.setCustomAnimations(R.anim.push_left_in, R.anim.push_right_out);
        }

        if (currentFragment == null) {
            transaction.add(R.id.fragment_content, fragment);
        }
        //如果之前没有添加过
        else if (!fragment.isAdded()) {
            transaction.hide(currentFragment).add(R.id.fragment_content, fragment);
        } else {
            transaction.hide(currentFragment).show(fragment);
        }
        //全局变量，记录当前显示的fragment
        currentFragment = fragment;
        transaction.commit();
    }

    @Override
    public void onClick(View v) {
        Integer tag = (Integer) v.getTag();
        // 点击当前标签获取其tag,并设置选中
        select(tag);
        showFragment2(fragmentList.get(tag));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusManager.unregister(this);
    }

    /**
     * 默认 http异常提醒
     *
     * @param userInfoChangedEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    @SuppressWarnings("unused")
    public void onEvent(UserInfoChangedEvent userInfoChangedEvent) {
        if (isFinishing()) {
            return;
        }
        LogUtil.d(TAG, "更新用户信息");
        LoginLogic.getUserInfo(this, new CommonCallback<UserBean>() {
            @Override
            public void onSuccess(UserBean userBean, CommonMessage commonMessage, String allResponseString) {
                if (userBean != null) {
                    UserInfoManager.saveUserDetailInfo(userBean);
                    EventBusManager.postSticky(new UserInfoChangedSuccessEvent(userBean));
                    LogUtil.d(TAG, "更新用户信息成功");
                } else {
                    LogUtil.d(TAG, "更新用户信息失败");
                }
            }

            @Override
            public boolean onFailure(int httpCode, Exception exception, CommonMessage responseMessage, String allResponseString) {
                LogUtil.d(TAG, "更新用户信息失败::" + allResponseString);
                return true;
            }
        });
    }

    /**
     * 默认 http异常提醒
     *
     * @param defalutHttpExceptionAlert
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    @SuppressWarnings("unused")
    public void onEvent(DefalutHttpExceptionAlert defalutHttpExceptionAlert) {
        if (isFinishing()) {
            return;
        }
        if (defalutHttpExceptionAlert != null) {
            alert(defalutHttpExceptionAlert.getErrorMsg());
        }
    }

    /**
     * 修改tab小红点数量
     *
     * @param tabNumberChangedEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    @SuppressWarnings("unused")
    public void onEvent(TabNumberChangedEvent tabNumberChangedEvent) {
        if (isFinishing()) {
            return;
        }
        int tabPosition = tabNumberChangedEvent.getTabPosition();
        int number = tabNumberChangedEvent.getNumber();
        if (tabPosition >= 0 && tabPosition <= 3) {
            buttonList.get(tabPosition).setMessageNumber(number);
        }
    }

    public static int getCarNum() {
        return buttonList.get(IMainView.TAB_CART_FRAGMENT).getMessageNumber();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 点击返回按钮，退出系统
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - mExitTime) > mInterval) {
                alert("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                EventBusManager.post(new DeleteOrStopLoadEvent("stopDownload"));
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                mNotificationManager.cancelAll();
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
                    List<ActivityManager.AppTask> appTasks = activityManager.getAppTasks();
                    for (ActivityManager.AppTask appTask : appTasks) {
                        appTask.finishAndRemoveTask();
                    }
                } else {
                    finish();
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }, 150);
            }
            return true;
        }
        return false;
    }

    @Override
    public void updateData(int productSize) {
        buttonList.get(IMainView.TAB_CART_FRAGMENT).setMessageNumber(productSize);
    }
}
